<template>
  <div class="whole">
    <el-container>
      <el-container>
        <el-main>
          <div class="app-container">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              v-show="showSearch"
              label-width="100px"
            >
              <el-form-item label="部门名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入部门名称"
                  clearable
                />
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQuery"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh"
                  size="mini"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table
              v-if="refreshTable"
              v-loading="loading"
              :default-expand-all="isExpandAll"
              row-key="id"
              :data="departmentList"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="部门名称" prop="name" />
              <el-table-column label="用户人数" prop="userNumber" />
              <el-table-column label="排序" align="center" prop="sort" />
              <el-table-column
                label="编辑时间"
                align="center"
                prop="createTime"
              />
              <el-table-column
                label="更新时间"
                align="center"
                prop="updateTime"
              />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    >选择
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
  <script>
import {
  listDepartment,
  getDepartment,
  delDepartment,
  updateDepartment,
  listTreeDepartment,
  addDepartment,
} from "@/api/DepartmentManagement";
import Treeselect from "@riophae/vue-treeselect";
export default {
  name: "Department",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 总条数
      total: 0,
      // 是否展开子节点
      isExpandAll: true,
      // 表格数据
      departmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
      },
      // 弹框部门名称树选项
      classifyOptions: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log();
      listTreeDepartment(this.queryParams).then((response) => {
        this.departmentList = response.data.data;
        console.log(response);
      });
      this.loading = false;
      //   // console.log(response);
      //   // this.departmentList = this.handleTree(
      //   //   response.data.data.data,
      //   //   "id",
      //   //   "parentId"
      //   // );
      //   this.total = response.data.data.totalRecords;
      //   this.loading = false;
      // });
    },

    // 列表子节点折叠或者打开
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll; //切换子菜单
      // 需要表格重新绘制一下，否则会产生固定列位错误
      this.$nextTick(() => {
        this.refreshTable = true; //展开子菜单
      });
    },
    // 弹框部门分类下拉树结构
    getTreeselect() {
      listDepartment().then((response) => {
        this.classifyOptions = []; //定义一个数组
        const data = { id: 0, name: "顶级节点", children: [] };
        data.children = this.handleTree(
          response.data.data.data,
          "id",
          "parentId"
        ); //根据（子菜单的pid=父级的id）来查找树节点//展示数据
        this.classifyOptions.push(data); //push()往数组后面添加元素
        console.log(this.classifyOptions);
      });
    },
    // 弹框部门分类数据结构
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userNumber: null,
        name: null,
        sort: 1,
      };
      this.$refs["queryForm"].resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getTreeselect(); //下拉树结构
      this.reset();
      this.open = true;
      this.title = "添加部门";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.getTreeselect(); //下拉树结构
      this.reset();
      const id = row.id || this.ids;
      getDepartment(id).then((response) => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改部门";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          if (this.form.id != null) {
            updateDepartment(this.form).then((response) => {
              console.log(response);
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.open = false;
              this.getList();
            });
          } else {
            addDepartment(this.form).then((response) => {
              console.log(response);
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除部门名称为"' + row.name + '"的数据项？')
        .then(function () {
          return delDepartment(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>u
  